﻿using System;
using Microsoft.VisualStudio.SharePoint;
using Microsoft.VisualStudio.SharePoint.Explorer;
using CodeCounsel.SharePoint.DevTools.Commands;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using Microsoft.VisualStudio.SharePoint.Explorer.Extensions;

namespace CodeCounsel.SharePoint.DevTools.ExplorerNodeExtensions
{
    [Export(typeof(IExplorerNodeTypeProvider)),
    ExplorerNodeType(NodeIDs.ThemeNode)]
    public class ThemeNodeTypeProvider
        : IExplorerNodeTypeProvider
    {
        internal static void CreateThemeNodes(IExplorerNode parentNode)
        {
            ItemInfo[] themes = parentNode.Context.SharePointConnection.ExecuteCommand<ItemInfo[]>(CommandIDs.GetThemes);
            foreach (ItemInfo theme in themes)
            {
                CreateNode(parentNode, theme);
            }
        }

        internal static IExplorerNode CreateNode(IExplorerNode parentNode, ItemInfo theme)
        {
            Dictionary<object, object> annotations = new Dictionary<object, object>();
            annotations.Add(typeof(ItemInfo), theme);
            return parentNode.ChildNodes.Add(NodeIDs.ThemeNode, theme.Name, annotations);
        }

        public void InitializeType(IExplorerNodeTypeDefinition typeDefinition)
        {
            typeDefinition.IsAlwaysLeaf = true;
            typeDefinition.NodePropertiesRequested += NodePropertiesRequested;  
        }

        void NodePropertiesRequested(object sender, ExplorerNodePropertiesRequestedEventArgs e)
        {
            ItemInfo itemInfo = e.Node.GetAnnotation<ItemInfo>();
            Dictionary<string, string> masterPageProperties = e.Node.Context.SharePointConnection.ExecuteCommand<ItemInfo, Dictionary<string, string>>(CommandIDs.GetThemeProperties, itemInfo);
            object propertySource = e.Node.Context.CreatePropertySourceObject(masterPageProperties);
            e.PropertySources.Add(propertySource);
        }
    }
}
